package com.koomii.myproject.springmvc;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import com.koomii.myproject.common.MessageBean;
import com.koomii.myproject.exception.BussinessException;

public class CustMappingExceptionResolver extends SimpleMappingExceptionResolver {

	@Override
	protected ModelAndView doResolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		HandlerMethod mathod = (HandlerMethod) handler;
        ResponseBody body = mathod.getMethodAnnotation(ResponseBody.class);
        if (body == null) {
            return super.doResolveException(request, response, handler, ex);
        }
        ModelAndView mv = new ModelAndView();
        //设置状态码
        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        //设置ContentType
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        //避免乱码
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Cache-Control", "no-cache, must-revalidate");
        try {
        	MessageBean msg = new MessageBean();
        	msg.fireFailed();
        	
        	if(ex instanceof BussinessException) {
        		msg.setMessage(ex.getMessage());
        	} else {
        		msg.setMessage("系统异常,请联系管理员");
        	}
        	
        	logger.debug("系统异常",ex);
            response.getWriter().write(JSONObject.fromObject(msg).toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return mv;
	}

}
